package org.mclll.xwangplugin.questTracking.questGoal;

import me.pikamug.quests.events.quester.BukkitQuesterPostUpdateObjectiveEvent;
import me.pikamug.quests.quests.components.BukkitObjective;
import me.pikamug.quests.quests.components.Stage;
import net.md_5.bungee.api.ChatColor;
import org.bukkit.DyeColor;
import org.bukkit.scoreboard.Objective;
import org.jetbrains.annotations.NotNull;
import org.mclll.xwangplugin.questTracking.persistence.Persistence;
import org.mclll.xwangplugin.util.GetChineseNameUtil;

import java.util.LinkedList;
import java.util.List;

/**
 * @author: geduo
 * @date: 2023/10/13 16:02
 */
public class CutWoolQuestTrack {

    private static final String FORMAT_PREFIX = "给%s羊剪毛";
    private static final String LINE_FORMAT = FORMAT_PREFIX + " (%d/%d)";
    public static void questTracking(Objective context, Integer line, Stage questsStage) {
        LinkedList<DyeColor> sheepToShear = (LinkedList<DyeColor>) questsStage.getSheepToShear();
        if (sheepToShear.isEmpty()) {
            return;
        }
        LinkedList<Integer> sheepNumToShear = questsStage.getSheepNumToShear();
        for (int i = 0; i < sheepToShear.size(); i++) {
            DyeColor dyeColor = sheepToShear.get(i);
            Integer num = sheepNumToShear.get(i);
            context.getScore(getGoalFormat(dyeColor, 0, num)).setScore(line--);
        }
    }

    @NotNull
    public static String getGoalFormat(DyeColor dyeColor, Integer progress, Integer total) {
        return ChatColor.YELLOW + String.format(LINE_FORMAT, GetChineseNameUtil.get(dyeColor), progress, total);
    }
    @NotNull
    public static String getFinishFormat(DyeColor dyeColor) {
        return ChatColor.GRAY + String.format(FORMAT_PREFIX, GetChineseNameUtil.get(dyeColor)) + " (✓)";
    }

    public static void goalFinish(BukkitQuesterPostUpdateObjectiveEvent event, List<Persistence.SerializeScore> scoreboard) {
        BukkitObjective questObj = (BukkitObjective) event.getObjective();
        DyeColor woolColor = (DyeColor) questObj.getGoalObject();
        for (Persistence.SerializeScore score : scoreboard) {
            String entry = score.getName();
            String colorName = GetChineseNameUtil.get(woolColor);
            if (entry.startsWith(ChatColor.YELLOW +String.format(FORMAT_PREFIX, colorName))) {
                int total = questObj.getGoal() - questObj.getProgress();
                if (total == 0) {
                    score.setName(getFinishFormat(woolColor));
                    score.setValue(scoreboard.get(scoreboard.size() - 1).getValue() - 1);
                } else {
                    score.setName(getGoalFormat(woolColor, questObj.getProgress(), questObj.getGoal()));
                }
            }
        }
    }


}
